class FriendController < ApplicationController
  layout "friend"
  
  before_filter :authorize, :except => :user
  
  def index
    @is_myself = true
    @user = get_current_user(session[:user_name])
    if params[:opt] == "f"
      @page_title = "#{@user.display_name}'s Followers_Microblog"
      @relation = "follower"
      @list_items = get_followers(@user.id)
    else
      @page_title = "#{@user.display_name}'s Friends_Microblog"
      @relation = "friend"
      @list_items = get_friends(@user.id)
    end
  end
  
  def user
    current_user = get_current_user(session[:user_name])
    @user = User.find(params[:id])
    # redirect to index if oneself
    if (current_user.id.to_s == params[:id] and params[:opt] == "f")
      redirect_to(:controller => :friend, :action => "index", :opt => "f")
    elsif (current_user.id.to_s == params[:id])
      redirect_to(:controller => :friend, :action => "index")
    elsif params[:opt] == "f"
      # do normal follower list
      @list_items = get_followers(params[:id])
      @relation = "follower"
      @page_title = "#{@user.display_name}'s Followers_Microblog"
      render(:controller => :friend, :action => "index")
    else
      # do normal friend list
      @list_items = get_friends(params[:id])
      @relation = "friend"
      @page_title = "#{@user.display_name}'s Friends_Microblog"
      render(:controller => :friend, :action => "index")
    end
    
  end

  def add
    # Open up friends and requests table for write
    user = get_current_user(session[:user_name])
    friend_ids = []
    # Friend request judgetment will not added until privacy is implemented.
    # right now, you add a friend, and he/she is in your friendlist.
    # Judge if he/she is in your friendlist will be enough to
    # avoid sending request repeatedly.
    Follower.get_friend_list(user.id).each do |f|
      friend_ids << f.user_id
    end
    name = User.find(params[:id]).display_name
    # ignore the cases while a user try to add oneself or an existing friend again
    if params[:id] == user.id.to_s
      flash[:notice] = "You cannot add yourself friend."
    elsif friend_ids.include?(params[:id].to_i)
      flash[:notice] = "#{name} is already in your friends list."
    else
      follow = Follower.new
      follow_request = Request.new
      follow.user_id = follow_request.user_id= params[:id]
      follow.follower_id = follow_request.requester_id = user.id
      follow.follow_since = follow_request.request_at= Time.now
      if follow.save and follow_request.save
        flash[:notice] = "You've successfully added #{name} as your friend."
      else
        flash[:notice] = "Failed to add #{name} as your friend."
      end
    end
      uri = session[:ori_uri]
      session[:ori_uri] = nil
      redirect_to( uri || {:controller => :message, :action => "index"} )
  end

  def delete
    name = User.find(params[:id]).display_name
    current_user = get_current_user(session[:user_name])
    follow = get_follower_by_user_id(current_user.id, params[:id])
    # judge if the friend request is still not dealed by the host.
    # if so, delete the request.
    request = get_request_by_user_id(current_user.id, params[:id])
    # do the delete
    if follow.destroy
      request.destroy unless request.nil?
      flash[:notice] = "You've successfully deleted #{name}."
    else
      flash[:notice] = "Failed to delete #{name}."
    end
    uri = session[:ori_uri]
    session[:ori_uri] = nil
    redirect_to( uri || {:controller => :message, :action => "index"} )
  end
  
  private
  
  def get_current_user(name)
    users = User.find(:all, :conditions => ["name='#{name}'"])
    users[0]
  end
  
  def get_friends(id)
    friend_id_list = Follower.get_friend_list(id)
    friends = []
    friend_id_list.each do |f|
      friends << User.find(f.user_id)
    end
    friends
  end
  
  def get_followers(id)
    follower_id_list = Follower.get_follower_list(id)
    followers = []
    follower_id_list.each do |f|
      followers << User.find(f.follower_id)
    end
    followers
  end
  
  # salve the data fatch the dirty way.... Orz  
  def get_request_by_user_id(me_id, u_id)
    # Assume I have controlled the duplication of requests, so just fetch the first one.
    Request.find_by_sql("SELECT * FROM requests WHERE user_id='#{u_id}' and requester_id='#{me_id}'")[0]
  end
  
  def get_follower_by_user_id(me_id, u_id)
    Follower.find_by_sql("SELECT * FROM followers WHERE user_id='#{u_id}' and follower_id='#{me_id}'")[0] #debug
  end
  
end
